package com.helu.lubike.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.Circle;
import com.amap.api.maps2d.model.CircleOptions;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.helu.lubike.R;
import com.helu.lubike.utils.SensorEventHelper;
import com.helu.lubike.utils.Utils;
import com.helu.lubike.activity.BluetoothMainActivity;
import com.helu.lubike.activity.MainActivity;
import com.helu.lubike.databinding.FragMainBinding;

import java.util.HashMap;
import java.util.Map;

/**
 * @author helu  17-2-7 下午1:16
 * @description
 */

public class MainFragment extends Fragment implements LocationSource, AMapLocationListener, GeocodeSearch.OnGeocodeSearchListener {

    private FragMainBinding inflate;
    private MainActivity activity;
    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    private SensorEventHelper mSensorHelper;
    private Circle mCircle;
    private Marker mLocMarker;
    private boolean mFirstFix;
    public static final String LOCATION_MARKER_FLAG = "mylocation";
    private Map<String, Marker> marksContainer;
    private GeocodeSearch geocoderSearch;
    private AMapLocation nowAMapLocation;
    private String mNowCheckMarker;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        inflate = DataBindingUtil.inflate(inflater, R.layout.frag_main, null, false);
        activity = (MainActivity) getActivity();
        inflate.map.onCreate(savedInstanceState);


        initView();
        initListener();
        return inflate.getRoot();
    }

    private void initView() {
        marksContainer = new HashMap<>();
        if (aMap == null) {
            aMap = inflate.map.getMap();
            setUpMap();
        }

        mSensorHelper = new SensorEventHelper(getContext());
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }

    }

    private void initListener() {
        inflate.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.mDrawerLayout.openDrawer(GravityCompat.START);
            }
        });


        inflate.sm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Utils.showToast(getContext(), "扫二维码解锁车");
            }
        });

        inflate.lydw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), BluetoothMainActivity.class));
            }
        });

        inflate.yuyue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.showToast(getContext(), "开始预约车啦");
                inflate.bottonBar2.setVisibility(View.GONE);
                inflate.bottonBar.setVisibility(View.VISIBLE);
            }
        });


        //定位按钮
        inflate.zcdw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mlocationClient.startLocation();
            }
        });

        inflate.shuaxin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RotateAnimation rotateAnimation = new RotateAnimation(0, 1080, inflate.shuaxin.getWidth() / 2, inflate.shuaxin.getHeight() / 2);
                rotateAnimation.setDuration(1000);
                inflate.shuaxin.setAnimation(rotateAnimation);
                getBikeToMap();
                inflate.shuaxin.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        //设置希望展示的地图缩放级别
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false

        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(false); //是否允许显示缩放按钮

        geocoderSearch = new GeocodeSearch(getContext());
        geocoderSearch.setOnGeocodeSearchListener(this);
    }


    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(getContext());
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        nowAMapLocation = amapLocation;
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                LatLng location = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                if (!mFirstFix) {
                    mFirstFix = true;
                    addCircle(location, amapLocation.getAccuracy());//添加定位精度圆
                    addMarker(location);//添加定位图标
                    mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转

                    getBikeToMap();

                } else {
                    mCircle.setCenter(location);
                    mCircle.setRadius(amapLocation.getAccuracy());
                    mLocMarker.setPosition(location);
                }
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));
                mlocationClient.stopLocation();
            } else {
                Log.d("MAINFRAG", "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo());
            }
        }
    }


    /**
     * 在地图上显示小路单车
     */
    private void getBikeToMap() {
        if (marksContainer != null) {
            clearAllBike();
        }

        for (int i = 0; i < 3; i++) {
            double sjs1 = 0.00040 - Math.random() * 0.00080;
            double sjs2 = 0.00040 - Math.random() * 0.00080;
            //模拟添加小车
            addMarkersToMap(new LatLng(nowAMapLocation.getLatitude() + sjs1, nowAMapLocation.getLongitude() + sjs2), "LU-00" + (i + 1));
        }
    }


    private void clearAllBike() {
        for (Map.Entry<String, Marker> entry : marksContainer.entrySet()) {     //删除所有的小车
            entry.getValue().remove();
        }
    }

    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);

    private void addCircle(LatLng latlng, double radius) {
        CircleOptions options = new CircleOptions();
        options.strokeWidth(1f);
        options.fillColor(FILL_COLOR);
        options.strokeColor(STROKE_COLOR);
        options.center(latlng);
        options.radius(radius);
        mCircle = aMap.addCircle(options);
    }

    private void addMarker(LatLng latlng) {
        if (mLocMarker != null) {
            return;
        }
        Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                R.mipmap.navi_map_gps_locked);
        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mLocMarker = aMap.addMarker(options);
    }

    /**
     * 在地图上添加marker
     */
    private void addMarkersToMap(final LatLng latlng, String title) {
        final Marker marker = aMap.addMarker(
                new MarkerOptions().position(latlng).title(title).icon(
                        BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.getResources(),
                                R.mipmap.bike_marker))));
        marksContainer.put(title, marker);

        // 定义 Marker 点击事件监听
        AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
            // marker 对象被点击时回调的接口
            // 返回 true 则表示接口已响应事件，否则返回false
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getTitle() == null || (marker.getTitle() != null && !marker.getTitle().startsWith(getString(R.string.bikeNamePrifix)))) {
                    return true;
                }

                if (mNowCheckMarker != null) {
                    marksContainer.get(mNowCheckMarker).setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(MainFragment.this.getResources(),
                            R.mipmap.bike_marker)));
                }

                mNowCheckMarker = marker.getTitle();

                marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(MainFragment.this.getResources(),
                        R.mipmap.bike_marker2)));

                inflate.bottonBar.setVisibility(View.GONE);
                inflate.bottonBar2.setVisibility(View.VISIBLE);
                inflate.clbhS.setText(marker.getTitle());
                inflate.dzxs.setText("");

                float distance = AMapUtils.calculateLineDistance(latlng, new LatLng(nowAMapLocation.getLatitude(), nowAMapLocation.getLongitude()));
                inflate.bxjl.setText("约" + Utils.format2xNum(distance) + "米");
                inflate.bxsj.setText("需" + Utils.format2xNum(distance / 67) + "分钟");

                // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(marker.getPosition().latitude, marker.getPosition().longitude), 200, GeocodeSearch.AMAP);
                geocoderSearch.getFromLocationAsyn(query);
                return true;
            }
        };


        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (mNowCheckMarker != null) {
                    marksContainer.get(mNowCheckMarker).setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(MainFragment.this.getResources(),
                            R.mipmap.bike_marker)));
                    mNowCheckMarker = null;
                }
                inflate.bottonBar2.setVisibility(View.GONE);
                inflate.bottonBar.setVisibility(View.VISIBLE);
            }
        });


        // 绑定 Marker 被点击事件
        aMap.setOnMarkerClickListener(markerClickListener);


        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                inflate.shuaxin.setVisibility(View.VISIBLE);
            }
        });
    }


    //-------------------AMap的状态同步--------------------------------
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        inflate.map.onDestroy();

        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        inflate.map.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        inflate.map.onResume();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        inflate.map.onSaveInstanceState(outState);
    }


    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        //根据经纬度查询到了位置
        inflate.dzxs.setText(regeocodeResult.getRegeocodeAddress().getFormatAddress());
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
}
